#!/usr/bin/python3
from pyftpdlib.handlers import FTPHandler
from pyftpdlib.servers import FTPServer
from pyftpdlib.authorizers import DummyAuthorizer
from pyftpdlib.log import logger
import threading
import os
import time
from random import randint
#from dacid_dht import Dht
import hashlib
import subprocess
from subprocess import check_output

servisdir="./servisler"
#HOST = "127.0.0.1"
PORT = 2121
dhtsunucu="10.45.2.129:1923"
#dhtsunucu=None # 10.45.2.127:1923
servis="/ftp-tarama/"

def get_interface():
	for index, item in enumerate(os.listdir("/sys/class/net")):
		if "wg" in item:
			return item
			
#f = os.popen('ifconfig '+get_interface()+' | grep "inet\ addr" | cut -d: -f2 | cut -d" " -f1')
#HOST=f.read().strip('\n')
HOST="192.168.100.3"
# nmap ile port-tarama servisinin gerçeklenmesi
def port_tarama(param,client_dir):
    """thread worker function"""
    updir=servisdir+servis+client_dir+"/"
    host=param.split(":")[0]
    port=param.split(":")[1]
    # portu tara- rapor oluştur
    subprocess.call(['python3','./ftpworm.py',"-H",host,"-p",port, "-o",updir+"raporT"])
    subprocess.call(['mv',updir+"raporT", updir+"rapor"])
    return

# sunucunun kendini diğer düğümler tarafından bulunmasını sağlamak için DHT sunucusuna kayıt ettirmesi.
def dht_kayit_islemi():
	while 1:
		bilgi=str(HOST)+":"+str(PORT)
		#sunucu dht ye kayıt edilecek.
		print ("sunucu dht ye kayıt edilecek.")
		#dht=Dht(bs=dhtsunucu)
		#if dht.sunucu_kayit(bilgi):
		#	logger.info("Sunucu milisia-dht (%s) kaydı yapıldı.",(dht.sunucu))
		# 5dk da bir kendini dht suncusuna kayıt ettirecek.
		logger.info("Sunucu milisia-dht (%s) kaydı yapıldı.",(dhtsunucu))
		time.sleep(300)

class MyHandler(FTPHandler):

    def istemci_hash(self,ip,port):
        ipport_str=str(ip)+"@"+str(port)
        hasho = hashlib.sha1()
        hasho.update(ipport_str.encode('utf-8'))
        ihash_id=hasho.hexdigest()
        return ihash_id
        
    def request_handle(self,file,client_id):
        print ("dosya:",file)
        istek=open(file,"r").read()
        t = threading.Thread(target=port_tarama, args=(istek,client_id,))
        t.start()
    
    def on_connect(self):
        print ("%s:%s connected" % (self.remote_ip, self.remote_port))
        #self.banner(str(randint(100, 1999)))

    def on_disconnect(self):
        # do something when client disconnects
        id=self.istemci_hash(self.remote_ip, self.remote_port)
        subprocess.call(['rm','-rf', "./servisler"+servis+id])
        pass

    def on_login(self, username):
        print ("%s:%s logined" % (self.remote_ip, self.remote_port))
        id=self.istemci_hash(self.remote_ip, self.remote_port)
        print (">>>>",id,"bağlantı dizini oluşturuldu")
        self.push(id+"\n")
        subprocess.call(['mkdir',"-p","./servisler"+servis+id])
        pass

    def on_logout(self, username):
        # do something when user logs out
        pass

    def on_file_sent(self, file):
        # do something when a file has been sent
        pass

    def on_file_received(self, file):
        # do something when a file has been received
        print ("%s:%s dosya_gonderdi" % (self.remote_ip, self.remote_port))
        client_id=self.istemci_hash(self.remote_ip, self.remote_port)
        self.request_handle(file,client_id)
        pass

    def on_incomplete_file_sent(self, file):
        # do something when a file is partially sent
        pass

    def on_incomplete_file_received(self, file):
        # remove partially uploaded files
        import os
        os.remove(file)

    
        
def main():
	logger.info("sistem açıldı")
	# dht sunucu kayıt ettirme
	dhtkayit = threading.Thread(name='dht_kayit_islemi', target=dht_kayit_islemi)
	dhtkayit.setDaemon(True)
	dhtkayit.start()

	# ftp sunucu servis verme

	authorizer = DummyAuthorizer()
	#authorizer.add_user('user', '12345', homedir='.', perm='elradfmwMT')
	authorizer.add_anonymous(homedir='./servisler',perm='elradfmwMT')
	handler = MyHandler
	handler.authorizer = authorizer
	server = FTPServer((HOST,PORT), handler)
	server.serve_forever()

if __name__ == "__main__":
    main()
